package com.dwxt.parabolic.service;

import com.dwxt.parabolic.utils.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class FileService {
    @Value("${gate.file.uploadPath}")
    private String uploadPath;

    @Value("${gate.file.realPath}")
    private String realPath;

    @Value("${gate.file.server}")
    private String server;


    /**
     * 保存到本地
     *
     * @param file
     * @param fileName
     * @return
     * @throws IOException
     */
    public String saveFile(MultipartFile file, String fileName) throws IOException {

        log.info("保存文件开始");
        /**
         * 首先将文件缓存到服务器上
         */
        fileName = createFileName(file.getOriginalFilename(), fileName);
        String userId = RequestUtil.getCurrentCompanyId();

        File dir = new File(realPath + uploadPath + "/" + userId);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String savePath = realPath + uploadPath + "/" + userId + "/" + fileName;
        File saveFile = new File(savePath);
        file.transferTo(saveFile);
        // 先尝试压缩并保存图片
        //Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.25f).toFile(saveFile);
        // 设置访问权限，可读，所有人可读
        saveFile.setReadable(true, false);
        log.info("保存文件结束");
        return server + uploadPath + "/" + userId + "/" + fileName;
    }

    private String createFileName(String originalFilename, String fileName) {
        String result = "";
        // 获取文件后缀
        String suffix = getFileSuffix(originalFilename);
        if (StringUtils.isNotBlank(fileName)) {
            result = fileName + "." + suffix;
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String date = sdf.format(new Date());
            if (StringUtils.isNotBlank(suffix)) {
                result = date + "." + suffix;
            }
        }
        return result;
    }

    private String getFileSuffix(String fileName) {
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (StringUtils.isNotBlank(suffix)) {
            suffix = suffix.toLowerCase();
        }
        return suffix;
    }

    public List<String> saveEventFile(MultipartFile[] file) throws IOException {
        log.info("保存文件开始");
        /**
         * 首先将文件缓存到服务器上
         */
        //List<String> imgList = Arrays.asList("png", "jpg","jpeg");
        List<String> list = new ArrayList<>();
        for (MultipartFile multipartFile : file) {
            String fileName = multipartFile.getOriginalFilename();
            //String userId = RequestUtil.getCurrentCompanyId();
            File dir = new File(realPath + uploadPath + "/event");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String savePath = realPath + uploadPath + "/event/" + fileName;
            File saveFile = new File(savePath);
            multipartFile.transferTo(saveFile);
            // String fileSuffix = getFileSuffix(fileName);
            /*if (!imgList.contains(fileSuffix)) {
                multipartFile.transferTo(saveFile);
            } else {
                // 先尝试压缩并保存图片
                Thumbnails.of(multipartFile.getInputStream()).scale(1f).outputQuality(0.25f).toFile(saveFile);
            }*/
            // 设置访问权限，可读，所有人可读
            saveFile.setReadable(true, false);
            log.info("保存文件结束");
            String url = server + uploadPath + "/event/" + fileName;
            list.add(url);
        }

        return list;
    }

}
